<?php
namespace app\crm\model;
use think\Db;
use think\Model;
use think\Cache;

class Users extends Model
{
    /**
     * 缓存用户信息
     */
    protected function userscache ()
    {
        $result = Db::name('sys_users')->select();
        // 以工号为键
        foreach ($result as $val) {
            $users[$val['username']] = $val;
        }
        Cache::set('users', $users);
    }
	
	public function code()
	{
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L');
		$orderSn = $yCode[intval(date('Y')) - 2017] . $yCode[intval(date('m')) - 1] . sprintf('%02d', rand(10000, 99999));
		return $orderSn;
	}
	

    /**
     * 实现添加用户的功能
     * @param  [array] $data     [插入数据]
     * @return [int/bool]        [新增主键/false]
     */
    public function insertUser($data)
    {
        $user_count = Db::name('sys_users')->where("cn_name='". $data["cn_name"]."'")->count();
        if( $user_count>0 ){
            echo json_encode(array('msg'=>"此用户已存在！不能重复添加."));
            exit;
        }
		$data["username"] = $this->code().rand(0, 9);
		// $data["password"] = 'aj123456';
        $result = Db::name('sys_users')->insert($data);
        $this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'用户添加成功！'));
        } else {
            echo json_encode(array('msg'=>'用户添加失败！'));
        }

    }
	
	/**
     * 实现批量添加用户的功能
     * @param  [array] $data     [插入数据]
     * @return [int/bool]        [新增主键/false]
     */
    public function batchInsertUser()
    {
        
		$cn_name_arr = explode(',',$_REQUEST['cn_name']);
		for ($i=0; $i<count($cn_name_arr); $i++) {
		  
			$data[] = ['cn_name' =>$cn_name_arr[$i],'d_id'=>$_REQUEST['d_id'],'r_id'=>$_REQUEST['r_id'],'username'=>$this->code().$i];
		  
			$user_count = Db::name('sys_users')->where("cn_name='". $cn_name_arr[$i]."'")->count();
			if( $user_count>0 ){
				echo json_encode(array('msg'=>"名为 ".$cn_name_arr[$i]." 的用户已存在！不能重复添加."));
				exit;
			}
		} 
        $result = Db::name('sys_users')->insertAll($data);
        $this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'用户添加成功！'));
        } else {
            echo json_encode(array('msg'=>'用户添加失败！'));
        }

    }
	
	/**
     * 实现批量修改用户部门
     * @return [int/bool]        [新增主键/false]
     */
    public function batchChangeDepartment()
    {
		$d_id = $_REQUEST['department_id'];
		$result = Db::name('sys_users')->where('username in('.$_REQUEST['username'].')')->update(['d_id' => $d_id]);
		$this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'部门更换成功！'));
        } else {
            echo json_encode(array('msg'=>'部门更换失败！'));
        }
    }
	
	/**
     * 实现批量清空密码
     * @return [int/bool]        [新增主键/false]
     */
    public function clearPassword()
    {
		$username = $_REQUEST['username'];
		$result = Db::name('sys_users')->where("username in('".$_REQUEST['username']."')")->update(['password' => '']);
		$this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'密码清空成功！'));
        } else {
            echo json_encode(array('msg'=>'密码清空失败！'));
        }
    }
	
	/**
     * 批量设置IP
     * @return [type] [description]
     */
    public function batchUpdateIP()
    {
        $username = $_REQUEST['username'];
		$result = Db::name('sys_users')->where("username in(".$_REQUEST['username'].")")->update(['start_ip' => $_REQUEST['start_ip'],'end_ip' => $_REQUEST['end_ip']]);
		$this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'IP设置成功！'));
        } else {
            echo json_encode(array('msg'=>'IP设置失败！'));
        }

    }

    /**
     * 获取用户资料列表
     * @param str $where <查询条件>
     * @param int $page <页码>
     * @param int $limit <每页显示条数>
     * @return array <用户列表信息>
     */
    public function getUserData($where,$page,$limit)
    {
        $count = Db::name('sys_users')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $userList = Db::name('sys_users')->field("username,cn_name,en_name,r_id,d_id,email,phone,start_ip,end_ip")->where($where)->limit(($page-1)*$limit,$limit)->select();
        $role = Cache::get('role');
        $department = Cache::get('department');
        foreach ($userList as &$val) {
            $val["r_name"] = $role[$val["r_id"]]["r_name"];
            $val["department"] = $department[$val["d_id"]]["department_name"];
            $val["IP_range"] = $val["start_ip"].' - '.$val["end_ip"];
        }
        
        $rowsList = count($userList) ? $userList : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;

        return $arrData;
    }

    /**
     * 获取单个用户的信息
     * @param  str $username [用户账号]
     * @return arr           [用户信息]
     */
    public function getUserInfo($username)
    {
        $userInfo = Db::name('sys_users')->where('username',$username)->find();
        return $userInfo;
    }

    /**
     * 实现更新用户的功能
     * @param  [array] $data     [插入数据]
     * @return [int/bool]        [新增主键/false]
     */
    public function updateUser($username,$data)
    {
		$result = Db::name('sys_users')->where('username', $username)->update($data);
        $this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'更新成功！'));
        } else {
            echo json_encode(array('msg'=>'更新失败！'));
        }
    }

    /**
     * 删除用户
     * @param  str $username [用户账号]
     * @return [type]           [description]
     */
    public function deleteUsrs($username)
    {
        $result = Db::name('sys_users')->where("username in('".$_REQUEST['username']."')")->delete();
        $this->userscache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }
	
	public function getUsersList()
	{
		$result = Db::name('sys_users')->field("username,cn_name")->select();
		return $result;
	}

}